package com.apes.scm.masterdata.stock.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.masterdata.stock.model.Location;
import com.apes.scm.masterdata.stock.repository.LocationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 功能：库区信息
 *
 * @author HuJianlin
 * @create 2018-03-14 9:45
 */
@Service("locationService")
public class LocationService extends DomainService {
    @Autowired
    public LocationRepository locationRepository;

    public Location save(SimpleRequest request) {
        Location location = request.getO(Location.class);
        if (location.getId() == null) {
            location.setId(location.obtainLocationId(location));
        }
        return locationRepository.saveAndFlush(location);
    }

    public Location update(SimpleRequest request) {
        return save(request);
    }

    /**
     * 功能：
     *
     * @param request
     */
    public Page<Location> findAll(SimpleRequest request) {
        return locationRepository.findAll(PageRequest.of(request.get("page"), request.get("size")));
    }

    /**
     * 删除
     */
    public String delete(SimpleRequest request) {
        Location location = request.getO(Location.class);
        locationRepository.delete(location);
        return "删除成功";
    }
    /**
     * 功能：下拉模糊查询使用
     * @param request
     * @return
     */
    public Page<Location> find(SimpleRequest request) {
        String value = request.get("key");
        return locationRepository.find(value, value, PageRequest.of(request.get("page"), request.get("size")) );
    }

    /**
     * 老框架同步新框架仓库转换
     * @param request
     * @return
     */
    public Location queryTypeSal(SimpleRequest request) {
        JSONObject condition = request.getJO();
        JSONObject returnData = new JSONObject();
        List<Location> locationList = locationRepository.findAll(JpaDsl.toCriteriaByEq("phyDepot.origin", condition.getString("DDID"),/*"dept.id", condition.getString("DDID"), "dept.deptType.type.id",
                "businessClass", "dept.deptType.id", "000007",*/ "usage.id", condition.getString("KQID"), "valid", true));
        if (locationList.size() == 0) {
            locationList = locationRepository.findAll(JpaDsl.toCriteriaByEq("phyDepot.id", condition.getString("DDID"), "usage.id", condition.getString("KQID"), "valid", true));
            if (locationList.size() == 0) {
                throw new RuntimeException("根据地点未找到仓库有效物理仓，地点：" + condition.getString("DDID"));
            }
        }
        return locationList.get(0);
    }

    /**
     * 根据门店找带安库
     * @param dept
     * @return
     */
    public Location findProductRuleLocationByDept(Dept dept){
        List<Location> locations = locationRepository.findAll(JpaDsl.toCriteriaByEq("company.id",dept.getCompany().getId(),"usage.productRule",true,"valid",true));
        if(locations.size() == 0) return null;
        return locations.stream().findFirst().get();
    }

    public Location findLocationByDept(Dept dept,boolean productRule){
        Location loc = null;
        if(productRule){
            loc = findProductRuleLocationByDept(dept);
        }else{
            loc = locationRepository.findAll(JpaDsl.toCriteriaByEq("depot.dept.id",dept.getId(),"usage.id","1","valid",true)).stream().findFirst().orElse(null);
        }
        return loc;
    }

    /**
     * 获取对应单据的仓库
     * businessTypeId: 单据类型
     * usageId: 库区类型
     * key、name 输入值
     * @param simpleRequest
     * @return
     */
    public Page<Location> customizeConditionFind(SimpleRequest simpleRequest) {
        JSONObject getJO = simpleRequest.getJO();
        String key = getJO.getString("key");
        String name = "";
        String usageId = "1";
        String sceneId = "", companyId = "";
        int queryAll = 1;
        JSONArray filtersArray;
        if (getJO.get("condition")  == null) {
            name = key;
            filtersArray = getJO.getJSONObject("group").getJSONArray("filters");

        } else {
            JSONArray condition = getJO.getJSONArray("condition");
            if(condition.size() > 0) {
                key = condition.getJSONObject(0).getString("key");
            } else queryAll = 0;
            filtersArray = getJO.getJSONObject("domain").getJSONArray("filters");
        }
        for (int i = 0, iLen = filtersArray.size(); i < iLen; i++) {
            JSONObject filtersObj = filtersArray.getJSONObject(i);
            String field = filtersObj.getString("field");
            String value = filtersObj.getString("value");
            if ("scene".equals(field)) {
                sceneId = filtersObj.getString("value");
            } else if ("company".equals(field)) {
                companyId = value;
            }
        }
        usageId = "1";
        if ("HC002".equals(sceneId)) {
            usageId = "4";
        }

        Page<Location> locationPage = locationRepository.customizeConditionFind(queryAll, key, name, usageId, "ConsumableUse", companyId, PageRequest.of(getJO.getInteger("page"), getJO.getInteger("size")));
        return locationPage;
    }


    public List<Location> getLocationByDept(SimpleRequest request){
        String deptId = request.get("deptId").toString();
        List<Location> byDept = locationRepository.findByDept(deptId);
        if (byDept != null) return byDept;
        return null;
    }

    public boolean checkCompany(SimpleRequest request) {
        String id = request.get("id").toString();
        PartyRole company = SpringManager.getBean(PartyRoleRepository.class).findOne(id);
        return company.getParty().getPartyRoles().stream().anyMatch(partyRole -> partyRole.getRole().getId().equals("Warehousing"));
    }
}





















